﻿namespace Suture.Strategies
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;

    using Suture.Exceptions;

    public class ExplicitConstructorStrategy : IConstructorStrategy
    {
        private readonly Type targetType;

        private readonly IEnumerable<Type> typeArgs;

        public ExplicitConstructorStrategy(Type targetType, IEnumerable<Type> typeArgs)
        {
            this.targetType = targetType;
            this.typeArgs = typeArgs;
        }

        public ConstructorInfo GetConstructor(Dictionary<string, object> constructorArgs)
        {
            var matchingConstructor = this.targetType
                    .GetConstructors()
                    .SingleOrDefault(c => c.GetParameters().Select(p => p.ParameterType).SequenceEqual(this.typeArgs));

            if (matchingConstructor == null)
            {
                throw new ConstructorResolutionException(this.typeArgs.ToArray());
            }

            return matchingConstructor;
        }
    }
}